import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  menus: '',
  isAdmin: false,
  userInfo: undefined,
  allProjects: undefined,
  currentProject: undefined,
  includeMenuList: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PROJECTS: (state, projects) => {
    state.allProjects = projects
    if (!state.currentProject){
      state.currentProject = projects[0]
      sessionStorage.setItem("cityCode", projects[0].cityCode);
    }
  },
  SET_CURRENT_PROJECT: (state, project) => {
    state.currentProject = project
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_MENU_LIST: (state, includeMenuList) => {
    state.includeMenuList = includeMenuList
  },
  SET_ADMIN: (state, admin) => {
    state.isAdmin = admin
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_ADMIN', data.isAdmin === 1)
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        if (data.menuList) {
          let list = []
          data.menuList.forEach(v => {
            list.push(v)
          })
          commit('SET_MENU_LIST', list)
        }
        commit('SET_ADMIN', data.isAdmin === 1)
        commit('SET_USER_INFO', data)
        commit('SET_NAME', data.userRealName)
        commit('SET_AVATAR', 'http://jasobim.com:8085' + data.userIcon)
     
        commit('SET_PROJECTS', data.projectList)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      resetRouter()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },
  setCurrentProject({ commit }, project) {
    sessionStorage.setItem("cityCode", project.cityCode)
    commit('SET_CURRENT_PROJECT', project)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

